package com.msa.msaportal.controller;

import com.msa.msaportal.common.web.ConstantUntil;
import com.msa.msaportal.common.web.ResponseUtils;
import com.msa.msaportal.entity.UserComponent;
import com.msa.msaportal.service.IUserComponentService;
import com.msa.msaportal.util.RevokeThread;
import com.msa.msaportal.webservice.WebServiceTools;

import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.dom4j.DocumentException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xmlpull.v1.XmlPullParserException;

@Controller
@RequestMapping({"/portal"})
public class PortalAuthController
{

  @Resource(name="userComponentManager")
  private IUserComponentService userComponentManager;

  @RequestMapping({"/showAuthPage.do"})
  public String showAuthPage(HttpServletRequest request, HttpServletResponse response, HttpSession session, ModelMap model)
    throws IOException
  {
    Set roleSet = (Set)session.getAttribute("roleSet");
    Iterator it = roleSet.iterator();
    while (it.hasNext()) {
      System.out.println(it.next());
    }
    System.out.println((String)session.getAttribute("orgCode"));
    String wsdl = "http://198.10.10.133:7001/RMS/ComponentServices?wsdl";
    String method = "queryComponent";
    String param = "{'componentType':'福建组件'}";
    try {
      JSONArray componentTypes = JSONArray.fromObject(WebServiceTools.getDataByUrl(wsdl, method, param));
      JSONObject component = new JSONObject();
      component.put("node", "福建组件");
      System.out.println(roleSet.contains("CMP_001_R00005"));
      if ((roleSet.contains("CMP_001_R00005")) && ("08".equals((String)session.getAttribute("orgCode")))) {
        component.put("component", componentTypes);
        model.addAttribute("componentTypes", component.toString());
      } else {
    	String wsdl1 = "http://198.10.10.133:7001/RMS/ComponentServices?wsdl";
    	String method1 = "queryUserComponents";  
        JSONArray userComponents = JSONArray.fromObject(WebServiceTools.getDataByUrl(wsdl1, method1,(String)session.getAttribute("loginUserId")));
        Set componentSet = new HashSet();
        for (int i = 0; i < userComponents.size(); i++) {
          componentSet.add(userComponents.getJSONObject(i).getString("COMPONENT_ID"));
        }
        for (int i = 0; i < componentTypes.size(); ) {
          if (!componentSet.contains(componentTypes.getJSONObject(i).getString("componentId")))
            componentTypes.discard(i);
          else {
            i++;
          }
        }
        component.put("component", componentTypes);
        model.addAttribute("componentTypes", component.toString());
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    JSONArray userResult = new JSONArray();
    if (roleSet.contains("CMP_001_R00011")) {
      String url = "http://msa-xtgl-soa1:8011//CommissionInvoke/proxy/ContractLDAPService_BJproxy?wsdl";
      String methods = "getUsersByDeptNO";
      String parameter = (String)session.getAttribute("deptCode");
      try
      {
        JSONArray users = JSONArray.fromObject(WebServiceTools.getDataByUrl(url, methods, parameter));
        JSONObject deptUsers = new JSONObject();
        deptUsers.put("node", (String)session.getAttribute("deptName"));
        deptUsers.put("staff", users);
        userResult.add(deptUsers);
        model.addAttribute("users", userResult.toString());
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (roleSet.contains("CMP_001_R00005")) {
      JSONObject deptUsers = new JSONObject();
      try
      {
        String url = "http://msa-xtgl-soa1:8011/CommissionInvoke/proxy/LDAPService_BJproxy?wsdl";
        String methods = "RoleQueryServices_roleQueryUsersList";
        String parameter = "{'roleCode':'CMP_001_R00011','orgCode':'" + session.getAttribute("orgCode") + "','currentPage':'1','pageSize':'1000'}";
        JSONObject users = JSONObject.fromObject(WebServiceTools.getDataByUrl(url, methods, parameter));
        System.out.println(users);
        if ("1".equals(users.getString("result"))) {
          JSONArray staff = users.getJSONObject("datas").getJSONObject("table").getJSONObject("row").getJSONObject("table").getJSONArray("row");
          for (int i = 0; i < staff.size(); i++) {
            staff.getJSONObject(i).put("givenname", staff.getJSONObject(i).getString("userName") + "(" + staff.getJSONObject(i).getString("deptName") + ")");
            staff.getJSONObject(i).put("uid", staff.getJSONObject(i).getString("userId"));
          }
          deptUsers.put("node", "部门层级管理员");
          deptUsers.put("staff", staff);
          userResult.add(deptUsers);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      JSONObject orgUsers = new JSONObject();
      JSONArray orgUserArray = new JSONArray();
      if ("08".equals(session.getAttribute("orgCode"))) {
        String url = "http://msa-xtgl-soa1:8011/CommissionInvoke/proxy/LDAPService_BJproxy?wsdl";
        String methods = "OrgQueryServices_queryOrg4Detail";
        String parameter = "{'orgCode': '08','isQuerySubOrg':'1'}";
        try {
          JSONArray subOrg = JSONObject.fromObject(WebServiceTools.getDataByUrl(url, methods, parameter)).getJSONObject("datas").getJSONObject("table").getJSONObject("row").getJSONArray("table").getJSONObject(0).getJSONArray("row");
          System.out.println(subOrg);
          String url2 = "http://msa-xtgl-soa1:8011/CommissionInvoke/proxy/LDAPService_BJproxy?wsdl";
          String methods2 = "RoleQueryServices_roleQueryUsersList";
          for (int i = 0; i < subOrg.size(); i++) {
            String subOrgCode = subOrg.getJSONObject(i).getString("orgCode");
            String parameter2 = "{'roleCode':'CMP_001_R00005','orgCode':'" + subOrgCode + "','currentPage':'1','pageSize':'1000'}";

            JSONObject users = JSONObject.fromObject(WebServiceTools.getDataByUrl(url2, methods2, parameter2));
            if ("1".equals(users.getString("result"))) {
              JSONObject temp = new JSONObject();
              temp = users.getJSONObject("datas").getJSONObject("table").getJSONObject("row").getJSONObject("table").getJSONArray("row").getJSONObject(0);
              temp.put("givenname", temp.getString("userName") + "(" + temp.getString("orgName") + ")");
              temp.put("uid", temp.getString("userId"));
              orgUserArray.add(temp);
            }
          }
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
        orgUsers.put("node", "机构层级管理员");
        orgUsers.put("staff", orgUserArray);
        userResult.add(orgUsers);
      }
      System.out.println("users" + userResult.toString());
      model.addAttribute("users", userResult.toString());
    }
    return "/auth";
  }
  @RequestMapping({"/queryUserComponents.do"})
  public void queryUserComponents(HttpServletRequest request, HttpServletResponse response, HttpSession session, ModelMap model) throws IOException {
    String userId = request.getParameter("userId");
    JSONArray result = new JSONArray();
    String wsdl = "http://198.10.10.133:7001/RMS/ComponentServices?wsdl";
    String method = "queryUserComponents";
    try {
      result = JSONArray.fromObject(WebServiceTools.getDataByUrl(wsdl, method, userId));
    } catch (Exception e) {
      e.printStackTrace();
    }
    ResponseUtils.renderJson(response, result.toString());
  }
  @RequestMapping({"/saveUserComponents.do"})
  public void saveUserComponents(HttpServletRequest request, HttpServletResponse response, HttpSession session, ModelMap model) throws IOException {
    JSONObject param = JSONObject.fromObject(request.getParameter("data"));
    System.out.println(param);
    if (param.containsKey("auth")) {
      JSONArray authJSONArray = param.getJSONArray("auth");

      for (int i = 0; i < authJSONArray.size(); i++) {
        UserComponent userComponent = new UserComponent(authJSONArray.getJSONObject(i).getString("userId"), authJSONArray.getJSONObject(i).getString("componentId"));
        try {
          this.userComponentManager.insertUserComponent(userComponent);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    if (param.containsKey("revoke")) {
      JSONArray revokeJSONArray = param.getJSONArray("revoke");
      new RevokeThread(revokeJSONArray.toString()).start();
    }
    JSONObject result = new JSONObject();
    result.put("result", "1");
    result.put("info", "提交成功");
    ResponseUtils.renderJson(response, result.toString());
  }

  
  
  @RequestMapping({"/test.do"})
  public void test(HttpServletRequest request, HttpServletResponse response, HttpSession session, ModelMap model) throws IOException {
	Date date=new Date();
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String time=df.format(date);
	System.out.println("查osb前"+time);
	String url = "http://msa-xtgl-soa1:8011/CommissionInvoke/proxy/LDAPService_BJproxy?wsdl";
    String methods = "OrgQueryServices_queryOrg4Detail";
    String parameter = "{'orgCode': '08','isQuerySubOrg':'1'}";
    try {
		JSONArray subOrg = JSONObject.fromObject(WebServiceTools.getDataByUrl(url, methods, parameter)).getJSONObject("datas").getJSONObject("table").getJSONObject("row").getJSONArray("table").getJSONObject(0).getJSONArray("row");
	} catch (DocumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (XmlPullParserException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    Date date2=new Date();
	String time2=df.format(date2);
	System.out.println("查osb后"+time2);
    String wsdl = "http://198.10.10.133:7001/RMS/ComponentServices?wsdl";
    String method = "queryUserComponents";
    try {
      JSONArray.fromObject(WebServiceTools.getDataByUrl(wsdl, method, "350583198711282636"));
    } catch (Exception e) {
      e.printStackTrace();
    }
    Date date3=new Date();
	String time3=df.format(date3);
	System.out.println("查wsdl后"+time3);
	
	
	String wsdl1="http://198.20.38.46:8001/MSAPortal/ws/userTileServices?wsdl";
	String method1 ="getUserModules";  //appTaskId即该代办在原来系统中的ID，如果appTaskId userId appName在代办库已经有，则进行更新操作
	String param1 = "350583198711282636";
	try {
		WebServiceTools.getDataByUrl(wsdl1, method1,param1);
	} catch (DocumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (XmlPullParserException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	Date date4=new Date();
	String time4=df.format(date4);
	System.out.println("查自己的wsdl后"+time4);
  }
  
  @RequestMapping({"/portallogout.do"})
  public void portalLogout(HttpServletRequest request, HttpServletResponse response, HttpSession session)
    throws IOException
  {
    System.out.println("#####################################");
    System.out.println((String)session.getAttribute("orgCode"));
    session.removeAttribute("loginUserId");
    session.removeAttribute("productRoleid");
    session.removeAttribute("userName");
    session.removeAttribute("roleSet");
    session.removeAttribute("orgCode");
    session.removeAttribute("orgName");
    session.removeAttribute("deptCode");
    session.removeAttribute("deptName");
    System.out.println((String)session.getAttribute("orgCode"));
    response.sendRedirect(ConstantUntil.LOGOUT_URL);
  }

  public static void main(String[] args)
  {
    String wsdl = "http://127.0.0.1:7001/RMS/ComponentServices?wsdl";
    String method = "queryComponent";
    String param = "{'componentType':'福建组件'}";
    try {
      JSONArray componentTypes = JSONArray.fromObject(WebServiceTools.getDataByUrl(wsdl, method, param));
      String aa = "[{\"COMPONENT_ID\":\"19\"},{\"COMPONENT_ID\":\"21\"},{\"COMPONENT_ID\":\"30\"}]";
      JSONArray userComponents = JSONArray.fromObject(aa);
      Set componentSet = new HashSet();
      for (int i = 0; i < userComponents.size(); i++) {
        componentSet.add(userComponents.getJSONObject(i).getString("COMPONENT_ID"));
      }
      for (int i = 0; i < componentTypes.size(); ) {
        if (!componentSet.contains(componentTypes.getJSONObject(i).getString("componentId")))
          componentTypes.discard(i);
        else {
          i++;
        }
      }
      System.out.println(componentTypes);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}